package com.boom.springapp.javafxdemo.utils;

import java.io.File;
import java.net.URL;
import java.util.Enumeration;

/**
 * @author hhl
 * @version 1.0
 * @description
 * @date 2025/12/7 16:20
 */
public class ClasspathScanner {
    public static void main(String[] args) throws Exception {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

        // 获取classpath根目录
        URL classpathRoot = classLoader.getResource("china-provinces.geojson");
        System.out.println("Classpath root: " + classpathRoot);

        if (classpathRoot != null) {
            String path = classpathRoot.getPath();
            File rootDir = new File(path);

            if (rootDir.exists() && rootDir.isDirectory()) {
                System.out.println("Files and directories in classpath root:");

                File[] files = rootDir.listFiles();
                if (files != null) {
                    for (File file : files) {
                        if (file.isDirectory()) {
                            System.out.println("  [DIR]  " + file.getName());
                        } else {
                            System.out.println("  [FILE] " + file.getName());
                        }
                    }
                }
            } else {
                System.out.println("Classpath root is not a directory or doesn't exist.");
            }
        } else {
            System.out.println("Classpath root is null. Trying alternative approach...");

            // Alternative: Get classpath from system property
            String classpath = System.getProperty("java.class.path");
            System.out.println("System classpath: " + classpath);

            String[] paths = classpath.split(System.getProperty("path.separator"));
            for (String path : paths) {
                File dir = new File(path);
                if (dir.exists() && dir.isDirectory()) {
                    System.out.println("Found classpath directory: " + path);
                    File[] files = dir.listFiles();
                    if (files != null) {
                        for (File file : files) {
                            if (file.isDirectory()) {
                                System.out.println("  [DIR]  " + file.getName());
                            } else {
                                System.out.println("  [FILE] " + file.getName());
                            }
                        }
                    }
                    break; // Show only first valid directory
                }
            }
        }

        // Also try to list resources using getResources
        System.out.println("\nAll classpath roots:");
        Enumeration<URL> roots = classLoader.getResources("");
        while (roots.hasMoreElements()) {
            URL root = roots.nextElement();
            System.out.println("  Root: " + root);
        }
    }
}
